import JSEncrypt from 'jsencrypt'
/**
 * 陈夕 2021/4/9 下午3:45
 * desc: 序列化平铺的数据为树状数据，根据path
 * @params 路由数据 menu list
 **/
import {RouterConfig} from "../store/interface/MenuInterface";

export const formatMapToTree = (data: any, byWhat?: string) => {
    if (!byWhat) byWhat = 'path';
    let nMap: any = {}; // 新的循环关系mapping
    let nMapList: any = []; // data处理好之后的数组
    // 第一次循环得到当前的parent关系，为下一次循环建立依据
    for (let i = 0; i < data.length; i++) {
        let pathList = data[i][byWhat].split("/");
        pathList.shift();
        if (pathList.length === 1) { // 父级根
            if (pathList[0] === "") pathList[0] = "/"; // 空字符设置成root路径
            data[i]["parent"] = null;
            nMap[data[i][byWhat]] = data[i];
        } else {
            pathList.pop(); // 弹出最后一个
            data[i]["parent"] = "/" + pathList.join("/");
            nMap[data[i][byWhat]] = data[i];
        }
    }
    // 循环这个对象，因为对象引用关系，所以嵌套层级在这里处理
    for (let nMapKey in nMap) {
        if (nMap.hasOwnProperty(nMapKey) && nMap[nMapKey].parent && nMap[nMap[nMapKey].parent]) { // 父级存在 object
            if (nMap[nMap[nMapKey].parent]["children"] && nMap[nMap[nMapKey].parent]["children"].length) {
                nMap[nMap[nMapKey].parent]["children"].push(nMap[nMapKey]);
            } else {
                nMap[nMap[nMapKey].parent]["children"] = [nMap[nMapKey]];
            }
        } else {
            nMapList.push(nMap[nMapKey]);
        }
    }
    return {nMapList, nMap};
};

export const formatRouterRequireComponent = (value: RouterConfig[], Component: any) => {
    if (!value || !Component) return;
    for (let i = 0; i < value.length; i++) {
        value[i]['component'] = Component[value[i].path]
    }
    return value;
};

export const GetRSApass = (password: string) => {
    let jse = new JSEncrypt({})
    let publicString = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1JMt2FAoQs14WkIeRA/8EYU89kB4AeznfVm9w9QV33mb6Tmp3qPso3eoWnN0vAUgV3ecE9SYVJn7UwGjwmnDh+oGJ+Mls3P8GNH34iViBd8rTdQmqCbqLTWlKTNUWwK7EEXL0kJiA3UKQMFa1KQrO+Yn6dRS62Xr8S/CbUjoJlwIDAQAB`
    jse.setPublicKey(publicString)
    return jse.encrypt(password)
};

export const Throttle = (func: Function, wait = 50) => {
    let lastTime = 0;
    return (...args: any) => {
        let now = +new Date();
        if (now - lastTime > wait) {
            lastTime = now;
            func.apply(this, args)
        }
    }
};

export const getPrivacyPhone = (phone: string) => {
    if (!phone) return "";
    // @ts-ignore
    return phone.match(/(\d{3})(\d{4})(\d{4})/).slice(1).reduce(function (value, item, index) {
        return index === 1 ? value + "****" : value + item;
    })
}
